﻿using UnityEngine;
using System.Collections;

public class HpBar : MonoBehaviour {

	int maxHp;
	int curHp;
	float fillAmount;
	UISprite fillSprite;
	UISlider slider;
	UIFollowTarget followTarget;
	bool isPlayer;
	bool showHpBarOnChange;

	void Awake()
	{
		fillSprite = gameObject.transform.FindChild("fill").gameObject.GetComponent<UISprite>();
	}

	public void Init(PawnManifest _manifest, int _hp, bool _isPlayer)
	{
		isPlayer = _isPlayer;
		maxHp = _hp;
		curHp = _hp;
		fillAmount = 1.0f;
		fillSprite.enabled=true;
		if(fillSprite.type== UIBasicSprite.Type.Filled)
			fillSprite.fillAmount = fillAmount;
		else {
			if(slider==null)
				slider = fillSprite.gameObject.GetComponent<UISlider>();
			slider.value=1;
		}
		if(followTarget==null)
			followTarget = gameObject.AddComponent<UIFollowTarget>();
		followTarget.enabled=true;
		followTarget.target = _manifest.hudHeadTrans;
		followTarget.Init();
	}

	public void Clear()
	{
		followTarget.enabled=false;
	}

	public void UpdateHP(int _hp)
	{
		if(isPlayer) {
			if(!BattleSetting.Instance.showPlayerHpBar && !BattleSetting.Instance.showPlayerHpBarOnChange)
				return;
			showHpBarOnChange = BattleSetting.Instance.showPlayerHpBarOnChange;
		}
		else {
			if(!BattleSetting.Instance.showEnemyHpBar && !BattleSetting.Instance.showEnemyHpBarOnChange)
				return;
			showHpBarOnChange = BattleSetting.Instance.showEnemyHpBarOnChange;
		}
		gameObject.SetActive(true);
		curHp = _hp;
		fillAmount = (float)curHp/maxHp;
		if(fillSprite.type== UIBasicSprite.Type.Filled)
			fillSprite.fillAmount = fillAmount;
		else {
			slider.value = fillAmount;
		}
		if(curHp==0)
			fillSprite.enabled=false;

		if(showHpBarOnChange) {
			StopCoroutine("CoHideBar");
			StartCoroutine("CoHideBar");
		}
	}

	IEnumerator CoHideBar()
	{
		yield return new WaitForSeconds(BattleSetting.Instance.showHpBarTime);
		gameObject.SetActive(false);
	}
}
